package com.djx.案例.案例01;


import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.util.Date;


@Data
@Slf4j
public class MyConfigCenter implements Watcher {

    private final String myIP = "192.168.15.132:2181";
    static ZooKeeper zooKeeper;

    //用于本地化存储配置信息
    private String url;
    private String username;
    private String password;

    @SneakyThrows
    public void process(WatchedEvent watchedEvent) {

        if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
            System.out.println("连接成功！");
            log.info("----------------------------");

        } else if (watchedEvent.getState() == Event.KeeperState.Disconnected) {
            System.out.println("断开连接！");
        } else if (watchedEvent.getState() == Event.KeeperState.Expired) {
            System.out.println("会话超时！");
            zooKeeper = new ZooKeeper(myIP, 5000, this);
        } else if (watchedEvent.getState() == Event.KeeperState.AuthFailed) {
            System.out.println("认证失败！");
        } else if (watchedEvent.getType() == Event.EventType.NodeDataChanged) {
            zook01();

        }

    }

    /*
    连接zookeeper 服务器,读取配置信息
     */
    public void zook01() {
        try {
            zooKeeper = new ZooKeeper(myIP, 5000, this);


            this.url = new String(zooKeeper.getData("/config/url", true, null));
            this.password = new String(zooKeeper.getData("/config/password", true, null));
            this.username = new String(zooKeeper.getData("/config/username", true, null));

        } catch (Exception e) {
            log.info(e.getMessage());
        }

    }

    /**
     * 构造方法!
     */
    public MyConfigCenter() {
        zook01();
    }

    public static void main(String[] args) {
        try {
            MyConfigCenter myConfigCenter = new MyConfigCenter();
            while (true) {
                //三秒区读取一次配置信息
                Thread.sleep(5000);

                System.out.println("url:" + myConfigCenter.getUrl());
                System.out.println("password:" + myConfigCenter.getPassword());
                System.out.println("username:" + myConfigCenter.getUsername());
                System.out.println("********************" + new Date() + "**********************");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
